package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.StrategyComment;
import cn.wolfcode.wolf2w.business.mapper.StrategyCommentMapper;
import cn.wolfcode.wolf2w.business.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.business.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.context.SecurityContextHolder;
import cn.wolfcode.wolf2w.common.core.utils.StringUtils;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 攻略评论Service业务层处理
 * 
 * @author fang
 * @date 2024-09-27
 */
@Service
@Transactional
public class StrategyCommentServiceImpl extends ServiceImpl<StrategyCommentMapper, StrategyComment> implements IStrategyCommentService {
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Override
    public IPage<StrategyComment> queryPage(StrategyCommentQuery qo) {
        IPage<StrategyComment> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        LambdaQueryWrapper<StrategyComment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(StrategyComment::getCreateTime);
        lambdaQueryWrapper.eq(StrategyComment::getStrategyId,qo.getStrategyId());
        IPage<StrategyComment> pageResult = baseMapper.selectPage(page,lambdaQueryWrapper);
        //当前页面数据
        for (StrategyComment comment : pageResult.getRecords()) {
            Long userId = comment.getUserId();
            UserInfo data = remoteUserInfoService.getOne(userId, SecurityConstants.INNER).getData();
            comment.setUser(data);
        }
        return pageResult;
    }

    @Override
    public void add(StrategyComment comment) {
        //取出评论后，将空格变成null，然后将这个转换后的重新赋值给content
        comment.setContent(StringUtils.trimToNull(comment.getContent()));
        //断言工具类，设置边界
        AssertUtil.notNull(comment.getContent(),"评论内容不能为空");
        Long userId = SecurityContextHolder.getUserId();
        //用户的id
        comment.setUserId(userId);
        //当前时间
        comment.setCreateTime(new Date());
        comment.setState(0L);
        comment.setThumbnum(0L);
        baseMapper.insert(comment);
    }
}
